var express = require('express');
var router = express.Router();
// const uploader=require('@/../../../node_modules/express-fileupload')
const { extname, resolve } = require('path')
const { existsSync, appendFileSync, writeFileSync } = require('fs')


const app = express()//创建express实例

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
}); 
 
// //判断值
// const ALLOWED_TYPE = {
//   'video/mp4': 'mp4',
//   'video/ogg': 'ogg',
// }
 
//视频上传
router.post('/upload_video', async (req, res) => {
  let { name, size, type, fileName, uploadSize } = req.body
  console.log(name, size, type, fileName, uploadSize);
  const {file} = req.files

  if (!file) {
    res.send({
      code: 400,
      msg: '上传失败 为空'
    })
    return
  }
  if (!ALLOWED_TYPE[type]) {
    console.log(type, 'type');
    res.send({
      code: 1002,
      msg: '上传类型错误'
    })
    return
  }
  fileName = fileName + extname(name)
  const filePath = resolve(__dirname,'./uploads/' + fileName);

  console.log(filePath);
  //合并分片
  console.log(uploadSize, 'uploadSize');
  if (uploadSize !== 0) { // 判断文件是否存在
    if (!existsSync(filePath)) {
      res.send({
        code: 1001,
        msg: '上传失败'
      })
      return
    }
    appendFileSync(filePath, file.data)
    res.send({
      code: 0,
      msg: '添加数据成功'
    })
    return
  }
  writeFileSync(filePath, file.data)
  res.send({
    code: 200,
    msg: '上传成功asd'
  })
})


module.exports = router;
